import streamlit as st
import streamlit_authenticator as stauth
import yaml

from streamlit_authenticator.utilities.exceptions import (CredentialsError,
                                                          ForgotError,
                                                          LoginError,
                                                          RegisterError,
                                                          ResetError,
                                                          UpdateError) 
from mypages.myhome import home
from mypages.pokemon import plot_scatter

from mypages.school import school_table,citation_vs_rank_scatter

with open('st_auth/config.yaml') as file:
    config = yaml.load(file, Loader=yaml.SafeLoader)
    
authenticator = stauth.Authenticate(
    config['credentials'],
    config['cookie']['name'],
    config['cookie']['key'],
    config['cookie']['expiry_days'],
    config['pre-authorized']
)

def main():
    # 创建侧边栏登录
    try:
        authenticator.login()
    except LoginError as e:
        st.error(e)

    # 页面选择
    PAGES = {
        "Home": home,
        "Secure Page": secure_page,
        "Reset Password": reset_pwd,
        "宝可梦不同类的防御力和攻击力的对比": plot_scatter,
        "Update User Details": update_user_details,
        # "forgot_pwd": forgot_pwd,
        # "forgot_username": forgot_username,
        "logout":logout,
        '学校的数据表': school_table,
        '学校的引用与排名的关系': citation_vs_rank_scatter,
    }

    # 根据登录状态显示页面
    if st.session_state["authentication_status"]:
        st.sidebar.success(f'Logged in as {st.session_state["name"]}')
        page = st.sidebar.radio('Go to', list(PAGES.keys()))
        PAGES[page]()
    elif st.session_state["authentication_status"] == False:
        st.sidebar.error('Username/password is incorrect')
    elif st.session_state["authentication_status"] == None:
        st.sidebar.warning('Please enter your username and password')

def logout():
    authenticator.logout()
    
def reset_pwd():
    if st.session_state["authentication_status"]:
        try:
            if authenticator.reset_password(st.session_state["username"]):
                save()
                st.success('Password modified successfully')
        except ResetError as e:
            st.error(e)
        except CredentialsError as e:
            st.error(e)
            
def update_user_details():
    if st.session_state["authentication_status"]:
        try:
            if authenticator.update_user_details(st.session_state["username"]):
                save()
                st.success('Entries updated successfully')
        except UpdateError as e:
            st.error(e)
    

def secure_page():
    if st.session_state["authentication_status"]:
        st.title('Secure Page')
        st.write('This is a secure page only for authenticated users.')
    else:
        st.error("You are not logged in. Please log in to access the secure page.")
        
def save():
     with open('st_auth/config.yaml', 'w', encoding='utf-8') as file:
         yaml.dump(config, file, default_flow_style=False)

if __name__ == '__main__':
    main()